package com.shambles.manage2.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import com.shambles.manage2.exception.BaseException;
import com.shambles.manage2.exception.FileUploadException;
import com.shambles.manage2.service.FileService;
import com.shambles.manage2.tkmapper.entity.Photo;
import com.shambles.manage2.tkmapper.entity.RoomFile;
import com.shambles.manage2.tkmapper.entity.UploadFile;
import com.shambles.manage2.tkmapper.mapper.PhotoMapper;
import com.shambles.manage2.tkmapper.mapper.RoomFileMapper;
import com.shambles.manage2.tkmapper.mapper.UploadFileMapper;
import com.shambles.manage2.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lz
 * @description
 * @date 2019/5/20
 */
@SuppressWarnings("ALL")
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private UploadFileMapper uploadFileMapper;
    @Autowired
    private RoomFileMapper roomFileMapper;
    @Autowired
    private PhotoMapper photoMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String fileUpload(MultipartFile file) {

        String fileName = IdUtil.simpleUUID() + "_" + file.getOriginalFilename();
        File tarFile = tarFile = FileUtils.getFileByFileName(fileName);
        try {
            //将保存的文件对象
            file.transferTo(tarFile);
            //文件入库
            Photo photo = new Photo();
            photo.setImageUrl(FileUtils.getFileUrlPath(fileName));
            photo.setCreateTime(new Date());
            photo.setClassification(2);
            photoMapper.insert(photo);
        } catch (Exception e) {
            log.warn("文件入库异常!", e);
            if (tarFile.exists()) {
                tarFile.delete();
            }
            throw new FileUploadException(file.getOriginalFilename(), e);
        }
        //返回文件地址
        return FileUtils.getFileUrlPath(fileName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delFile(String fileGuid) {
        Example example1 = new Example(UploadFile.class);
        example1.createCriteria().andEqualTo("guid", fileGuid);
        uploadFileMapper.deleteByExample(example1);

        Example example = new Example(RoomFile.class);
        example.createCriteria().andEqualTo("fileGuid", fileGuid);
        roomFileMapper.deleteByExample(example);

        File file = FileUtils.getFileByFileName(fileGuid);
        if (file.exists()) {
            file.delete();
        }
    }
}
